package com.boxing.service;

import com.boxing.beans.Book;
import com.boxing.beans.HomeResult;
import com.boxing.beans.Result;
import com.boxing.beans.UserInfo;
import com.boxing.dao.BookDao;
import com.boxing.dao.UserDao;
import com.boxing.utils.Utils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class BookService {
    private  BookDao bookDao = new BookDao();
    private  UserDao userDao = new UserDao();


    public Result<HomeResult> searchBooks(HttpServletRequest request){
        String page = request.getParameter("page");
        String count = request.getParameter("count");
        System.out.println("==="+ page +"  "+ count);
        int pageInt=1,countInt=50;
        try {
            pageInt = Integer.parseInt(page);
            countInt = Integer.parseInt(count);
            if (pageInt < 1){
                pageInt = 1;
            }
            if (countInt < 10){
                countInt = 10;
            }
        }catch (Exception e){
            e.printStackTrace();
            Result<HomeResult> result = new Result<>();
            result.setCode(402);
            result.setMsg("参数列表不符合要求");
            return result;
        }
        List<Book> books = bookDao.searchBooks(pageInt, countInt);
        String contextPath = request.getContextPath();
        String requestURL = request.getRequestURL().toString();
        String substring = requestURL.substring(0, requestURL.indexOf(contextPath));
        // 拼接图片地址
        for(Book item : books){
            String img = item.getImg();
            item.setImg(substring + contextPath + img);
            item.setPrice(Utils.formatPrice(item.getPrice()));
        }
        // 获取用户名  从cookie、中取出token token为键在session中取出用户邮箱
        String userEmail = Utils.getUserEmailFromSession(request);
        // 获取商品表中的总数量
        long booksCount = bookDao.searchBooksCount();
        Result<HomeResult> result = new Result<>();
        result.setCode(200);
        result.setMsg("");
        HomeResult homeResult = new HomeResult();
        homeResult.setList(books);
        homeResult.setEmail(userEmail);
        UserInfo userInfo = userDao.unionEmail(userEmail);
        String userName="";
        if (userInfo != null){
            userName = userInfo.getUser();
        }
        homeResult.setName(userName==null?"":userName);
        System.out.println("======"+booksCount);
        homeResult.setCount(booksCount);

        result.setData(homeResult);
        return result;
    }

}
